package mytaxis.move.app;

import java.security.MessageDigest;

import mytaxis.move.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Login extends Activity {
	private EditText txtEmail;
	private EditText txtPass;
	private Button login;
	private ProgressDialog pd;
	private Thread serverCall;
	private String mail;
	private String pass;
	private MyTaxisApplication app;
	
	private MyTaxisService mBoundService;

	private ServiceConnection mConnection = new ServiceConnection() {
		public void onServiceConnected(ComponentName className, IBinder service) {
		    mBoundService = ((MyTaxisService.LocalBinder)service).getService();
		}
	
		public void onServiceDisconnected(ComponentName className) {
		    mBoundService = null;
		}
	};
	
	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			boolean result = msg.getData().getBoolean("result");
			if(result){
				Toast.makeText(getApplicationContext(),R.string.login_ok,0).show();
				mBoundService.setAvailable(app.isAvailable());
				Intent i = new Intent(Login.this, MenuActivity.class);
				startActivity(i);
				finish();
			}else{
				Toast.makeText(getApplicationContext(), R.string.login_wrong, Toast.LENGTH_SHORT).show();
			}
		};
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		initViews();
		startService(new Intent(Login.this, MyTaxisService.class));
		bindService(new Intent(this, MyTaxisService.class), mConnection, Context.BIND_AUTO_CREATE);
		app = (MyTaxisApplication) getApplication();
		if(app.getAuthToken()>0){
			Intent i = new Intent(this, MenuActivity.class);
			startActivity(i);
			finish();
		}
	}

	private void initViews() {
		txtEmail = (EditText) findViewById(R.id.EditTextEmail);
		txtPass = (EditText) findViewById(R.id.EditTextPass);
		login = (Button) findViewById(R.id.btnlogin);
		pd = new ProgressDialog(this);

		login.setOnClickListener(new Button.OnClickListener() {

			public void onClick(View v) {
				mail = txtEmail.getText().toString().trim();
				pass = txtPass.getText().toString().trim();
				if(mail.length() == 0 || pass.length() == 0) Toast.makeText(getApplicationContext(), 
						getApplicationContext().getString(R.string.user_pass_empty), Toast.LENGTH_SHORT).show();
				else{
					pd.setMessage("Connecting to server, this may take a few seconds.");
					pd.setTitle("Login");
					pd.show();
					
					serverCall = new Thread(new Runnable() {
						public void run() {							
							try{
								boolean login = mBoundService.login(mail, md5(pass));
								Message msg = new Message();
								Bundle b = new Bundle();
								b.putBoolean("result", login);
								msg.setData(b);
								mHandler.sendMessage(msg);
								pd.dismiss();
							}catch(Exception e){
								Log.e("Error",e.getMessage());
							}
						}
					});
					serverCall.start();
				}
			}
		});
	}
	
	public String md5(String s) {
	    try {
	        // Create MD5 Hash
	        MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
	        digest.update(s.getBytes());
	        byte messageDigest[] = digest.digest();
	        
	        // Create Hex String
	        StringBuffer hexString = new StringBuffer();
	        for (int i=0; i<messageDigest.length; i++)
	            hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
	        return hexString.toString();
	        
	    } catch (Exception e) {
	        Log.e("Error",e.getMessage());
	    }
	    return "";
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		unbindService(mConnection);
	}
	
	
}
